package org.linlinjava.litemall.wx.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.wx.util.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ： hejiaming
 * @createtime ： 2021-03-24 17:36
 * @description ： 提供给微信验证token
 */
@RestController
@RequestMapping("/")
public class WxTokenController {
    private final Log logger = LogFactory.getLog(WxTokenController.class);

    @Autowired
    private String wxConfigToken;

    /**
     * 提供给微信配置token使用
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/ac/?id=2")
    public String get(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("----------------验证微信服务号信息开始----------");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce, wxConfigToken)) {
            logger.info("----验证服务号结束.........");
            return echostr;
        } else {
            return "";
        }
    }
}
